package com.banciyuan.bcywebview.biz.groupdetail.info;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper.OnProgressCallbacks;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.groupdetail.TeamSettingActivity;
import com.banciyuan.bcywebview.biz.groupdetail.groupmember.GroupMemberActivity;
import com.banciyuan.bcywebview.biz.main.message.messagenewest.NewestMessageAdapter;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.Team;
import de.greenrobot.daoexample.model.TopPost;

/**
 * @author hfxt2008
 *         <p/>
 *         小组详细页面->小组信息页面
 */
public class TeamInfoActivity extends BaseActivity implements ActionbarHelper.OnActionCallbacks, OnClickListener {

    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private TextView mNameTv;
    private TextView mLikeTv;
    private Response.Listener<String> onInfoSuccess;
    private Response.ErrorListener onError;
    private RequestQueue mQueue;
    private String mGid = "";
    private View viewNoticBoard;
    private ImageLoader imageLoader;
    private Team team;
    private TextView creat_person;
    private LinearLayout llTopicMember;
    private String uid;
    private ListView listView;
    private View headView;
    private NewestMessageAdapter mAdapter;
    private List<TopPost> list = new ArrayList<TopPost>();
    private String member_num = "";
    private String isCreatoer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_teaminfo);
        initArgs();
        initProgressbar();
        initActionbar();
        initUi();
        initAction();
        initData();
        getTopListData();
    }

    public Context getContext() {
        return this;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void getTopListData() {
        String url = HttpUtils.BASE_URL + GroupApi.getListtopedposts();

        List<BcyPair> paramsList = new ArrayList<>();
        if (UserDataHelper.ifLogin(this))
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                JSONObject result = null;
                try {
                    result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, TeamInfoActivity.this)) {
                        Gson gson = new Gson();
                        list = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<TopPost>>() {
                        }.getType());
                        processData();
                    } else {
                        processData();
                    }
                } catch (Exception e) {
                    processData();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                processData();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, TeamInfoActivity.this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData() {
        if (mAdapter == null) {
            mAdapter = new NewestMessageAdapter(this, list);
            mAdapter.setListView(listView);
            listView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        if (list.size() > 0) {
            viewNoticBoard.setVisibility(View.VISIBLE);
        } else {
            viewNoticBoard.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        if (intent != null) {
            mGid = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
            team = (Team) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_TWO);
        }
        mQueue = VolleyQueue.getRquest(getContext());
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.topic_info));
        mActionbarHelper.setActionCallbacks(this);
    }

    @Override
    protected void initUi() {

        listView = (ListView) findViewById(R.id.listView);
        headView = View.inflate(this, R.layout.teaminfo_newlayout, null);

        creat_person = (TextView) headView.findViewById(R.id.tv_creator_name);
        mNameTv = (TextView) headView.findViewById(R.id.tv_topicname_name);
        mLikeTv = (TextView) headView.findViewById(R.id.tv_topicmumber);

        viewNoticBoard = headView.findViewById(R.id.rl_noticboard);
        llTopicMember = (LinearLayout) headView.findViewById(R.id.ll_topicmember);
        headView.findViewById(R.id.rl_member_desc).setOnClickListener(this);
        headView.findViewById(R.id.rl_creatorname).setOnClickListener(this);
        if (team != null && !TextUtils.isEmpty(team.getAdmin())) {
            creat_person.setText(team.getAdmin());
        }
        listView.addHeaderView(headView);
        onInfoSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getContext())) {
                    getInfoSuccess(response);
                }
            }
        };

        onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onNetworkError();
            }
        };
    }

    @Override
    protected void initData() {
        CommonApiUtils.getTeamInfo(this, mQueue, onInfoSuccess, onError, mGid);
    }

    public void onNetworkError() {
        mProgressbarHelper.onFailed();
    }

    private String avater;
    private String name;
    private String desc;

    public void getInfoSuccess(String result) {
        mProgressbarHelper.onSuccess();
        try {
            JSONObject mData = new JSONObject(result).getJSONObject(HttpUtils.UPLOAD_DATA);
            String mJson;
            isCreatoer = StringUtil.getFromJson(mData, "is_creator");
            desc = StringUtil.getFromJson(mData, "group", "intro");
            name = StringUtil.getFromJson(mData, "group", "name");
            uid = StringUtil.getFromJson(mData, "group", "uid");
            mJson = StringUtil.htmlDecoder(StringUtil.getFromJson(mData, "group", "name"));
            JSONArray members = mData.getJSONArray("members");
            member_num = StringUtil.getFromJson(mData, "group", "member_num");
            mNameTv.setText(mJson);
            if (!TextUtils.isEmpty(member_num) && !member_num.equals("0")) {
                mLikeTv.setText(String.format(getString(R.string.nums_focus_talk), member_num));
            } else {
                mLikeTv.setText(getString(R.string.noone_focus_talk));
            }
            if (StringUtil.notNullEqual(isCreatoer, "true")) {
                mActionbarHelper.addOneAction(R.drawable.edit_black);
            }
            int totalWidth = CommonUtils.getWidthPixels((this)) - UIUtils.dip2px(20, this);
            int memberViewWidth = UIUtils.dip2px(60, this);
            int maxLength = totalWidth / memberViewWidth;
            maxLength = maxLength > members.length() ? members.length() : maxLength;
            llTopicMember.removeAllViews();
            for (int i = 0; i < maxLength; i++) {
                View memberView = View.inflate(this, R.layout.teammember_head_layout, null);
                ImageView head = (ImageView) memberView.findViewById(R.id.head);
                JSONObject member = (JSONObject) members.get(i);
                String headUrl = StringUtil.getFromJson(member, "avatar");
                if (StringUtil.notNullStartWithUrlHead(headUrl)) {
                    imageLoader.displayImage(headUrl, head, ImageOptions.optionHead);
                } else {
                    head.setImageResource(R.drawable.user_pic_big);
                }
                final String uid = StringUtil.getFromJson(member, "uid");
                head.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        gotoUtil.gotoAct(TeamInfoActivity.this, SmoothPersonActivity.class, uid);
                    }
                });
                llTopicMember.addView(memberView);
            }

        } catch (JSONException e) {
        }
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {
        switch (id) {
            case R.id.base_action_bar_itemone:
                if (StringUtil.notNullEqual(isCreatoer, "true")) {
                    Intent intent = new Intent(this, TeamSettingActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, avater);
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, name);
                    intent.putExtra(gotoUtil.INTENT_VALUE_THREE, desc);
                    intent.putExtra("gid", mGid);
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_member_desc:
                if (!TextUtils.isEmpty(member_num) && !member_num.equals("0")) {
                    gotoUtil.gotoAct(this, GroupMemberActivity.class, mGid, member_num);
                }
                break;
            case R.id.rl_creatorname:
                if (!TextUtils.isEmpty(uid)) {
                    gotoUtil.gotoAct(this, SmoothPersonActivity.class, uid);
                }
                break;
        }
    }
}